<template>
  <div class="app-container">
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="98px">
      <el-form-item label="供应商名称" prop="providerId">
        <el-select
            v-model="queryParams.data.providerId"
            placeholder="请选择供应商名称"
            clearable
            size="small"
            style="width:180px">
          <el-option
              v-for="dict in providerOptions"
              :key="dict.providerId"
              :label="dict.providerName"
              :value="dict.providerId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="申请人" prop="applyUserName">
        <el-input
            v-model="queryParams.data.applyUserName"
            placeholder="请输入申请人"
            clearable
            size="small"
            style="width:180px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询条件结束 -->

    <!-- 表格工具按钮开始 -->

    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleAuditPass">
          审核通过
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="single" @click="handleAuditNoPass()">
          审核不通过
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleViewItem">
          查看详情
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格工具按钮结束 -->

    <!-- 数据表格开始 -->
    <el-table :data="purchaseTableList" @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="单据ID" align="center" width="200" prop="purchaseId"/>
      <el-table-column label="供应商" width="180" align="center" prop="providerId" :formatter="providerFormatter"/>
      <el-table-column label="采购批发总额" align="center" prop="purchaseTradeTotalAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.purchaseTradeTotalAmount|rounding }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="status"
          min-width="120"
          fixed="right"
          label="状态">
        <template v-slot="{row}">
          <div v-for="item in statusOptions" :key="item.dictValue" :disabled="row.status===1">
                        <span v-if="item.dictValue === row.status">
                            {{ item.dictLabel }}
                        </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUserName"/>
      <el-table-column label="入库操作人" align="center" prop="storageOptUser"/>
      <el-table-column label="入库时间" width="180" align="center" prop="storageOptTime"/>
      <el-table-column label="审核信息" align="center" prop="auditMsg"/>
      <el-table-column label="创建时间" width="180" align="center" prop="createTime"/>
    </el-table>
    <!-- 数据表格结束 -->


    <!--分页  -->
    <el-pagination
        :current-page="pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 单据详情的弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="1000px"
        center
        append-to-body
    >
      <el-table v-loading="loading" border :data="purchaseItemTableList">
        <el-table-column label="详情ID" width="180" align="center" prop="itemId"/>
        <el-table-column label="单据ID" width="200" align="center" prop="purchaseId"/>
        <el-table-column label="采购数量" align="center" prop="purchaseNumber"/>
        <el-table-column label="批发价" prop="tradePrice" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.tradePrice|rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批发额" align="center" prop="tradeTotalAmount">
          <template slot-scope="scope">
            <span>{{ scope.row.tradeTotalAmount|rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次号" align="center" prop="batchNumber"/>
        <el-table-column label="药品名称" align="center" prop="medicinesName"/>
        <el-table-column label="单位" align="center" prop="unit"/>
        <!-- <el-table-column label="创建时间" align="center" prop="unit" /> -->
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 单据详情的弹出层结束 -->
  </div>
</template>

<script>
export default {
  // 过滤器
  // filters: {
  //   // 保留两位小数
  //   rounding(value) {
  //     return value.toFixed(2)
  //     // return value
  //   }
  // },
  data() {
    return {
      // 是否启用遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否打开查看详情
      open: false,
      // 弹出层的标题
      title: '',
      total: 0,
      // 分页数据总条数
      pageNo: 1,
      //每页的大小
      pageSize: 5,
      // 表格数据
      purchaseTableList: [],
      // 单据详情情数据表格
      purchaseItemTableList: [],
      // 状态数据字典
      statusOptions: [],
      // 供应商的数据
      providerOptions: [],
      // 查询参数
      queryParams: {
        pageNo: undefined,
        //每页的大小
        pageSize: undefined,
        providerId: undefined,
        data: {},
        // applyUserName: undefined,
        // status: undefined,
      }
    }
  },
  created() {
    //查询状态
    this.$http.get("/stockRemoteDictData/queryByDictType?dictType=" + 'his_order_status').then(result => {
      this.statusOptions = result.data;
    })

    //查询所有可用的供应商
    this.$http.get("/provider/getAll").then(result => {
      this.providerOptions = result.data.data.data;
      // console.log(this.providerOptions)
    })

    //所有待审核数据
    this.loadTable()
  },
  // 方法
  methods: {
    // 加载表格数据
    loadTable() {
      // this.loading = true; // 打开遮罩
      this.queryParams.pageNo = this.pageNo;
      this.queryParams.pageSize = this.pageSize;
      this.$http.post("/purchase/queryByPageYesWaitForReview", this.queryParams).then(res => {
        // console.log(res.data.data)
        this.purchaseTableList = res.data.data.list;
        this.total = res.data.data.total;
      })
    },
    // 翻译供应商
    providerFormatter(row) {
      let name = ''
      this.providerOptions.filter(item => {
        if (parseInt(row.providerId) === parseInt(item.providerId)) {
          name = item.providerName
        }
      })
      return name
    },

    //查看详细
    handleViewItem() {
      this.open = true
      const purchaseId = this.ids[0]
      this.title = '单据编号为【' + purchaseId + '】的采购详情数据'
      return this.$http.get("/purchaseItem/getAllPurchaseItemByPurchaseId/" + purchaseId).then(res => {
        if (res.data.code === 200) {
          this.purchaseItemTableList = res.data.data;
          // 提示消息
          this.$notify({
            title: '成功',
            message: "成功！！！",
            type: 'success'
          });
        } else {
          this.$notify({
            title: '失败',
            message: res.data.data,
            type: 'warning'
          });
        }
      })
    },

    // 数据表格的多选择框选择时触发
    handleSelectionChnage(selection) {
      this.ids = selection.map(item => item.purchaseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    //审核通过
    handleAuditPass() {
      const purchaseId = this.ids[0]
      this.$prompt('请输入审核原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.$http.post("/purchase/updateStatus3/" + purchaseId+"/"+value).then(res => {
          if (res.data.code === 200) {
            this.$notify({
              title: '成功',
              message: "审核成功！！！",
              type: 'success'
            });
            this.loadTable();//
          } else {
            this.$notify({
              title: '失败',
              message: res.data.data,
              type: 'warning'
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });

      // const tx = this
      // tx.$confirm('是否确认审核通过单据ID为:' + purchaseId + '的数据?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(({value}) => {
      //   this.$http.post("/purchase/updateStatus3/" + purchaseId+"/"+value).then(res => {
      //     tx.$message.success("审核成功");
      //     tx.loadTable();//
      //   }).catch(() => {
      //     tx.$message.error("审核失败");
      //   });
      // })
      //     .catch(() => {
      //       tx.$message.error("审核取消");
      //     });
    },
    //审核不通过
    handleAuditNoPass(row) {
      const purchaseId = this.ids[0]
      //判断状态是否是待审核，如果不是不可执行
      this.$http.get("/purchase/queryById?id=" + purchaseId).then(res => {
        //单据状态； 1未提交2待审核 3审核通过 4审核失败 5作废 6入库成功 字典表 his_order_status
        if (res.data.data.status !== '2') {
          this.$message.error("该单据不是待审核状态，不能执行审核操作");
        } else {
          const tx = this
          tx.$prompt('请输入不通过的原因', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(({value}) => {    //4
            this.$http.get("/purchase/theReviewIsNotPassed/" + purchaseId + "/" + value)
                .then(res => {
                  tx.$message.success("审核成功");
                  tx.loadTable();//
                }).catch(() => {
              tx.$message.error("审核失败");
            });
          })
              .catch(() => {
                tx.$message.error("审核取消");
              });
        }
      })
    },
//取消
    cancel() {
      this.open = false
    },
    // 分页pageSize变化时触发
    handleSizeChange(val) {
      this.pageSize = val;
      // 重新查询
      this.loadTable();
    },
    // 点击上一页  下一页，跳转到哪一页面时触发
    handleCurrentChange(val) {
      this.pageNo = val;
      // 重新查询
      this.loadTable();
    },

    // 条件查询
    handleQuery() {
      this.loadTable();
    },
    // 重置查询条件
    resetQuery() {
      // this.queryParams = {};
      // this.loadTable();
      //页面刷新
      location.reload();
    },
  }
}
</script>

<style scoped>

</style>